package com.huitong.gateway.handler;

import com.huitong.gateway.utils.WebFluxUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关异常处理
 *
 * @author fromdrowning
 * @date 2024/3/17 15:34
 */
@Slf4j
@Order(-1)
@Configuration
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    /**
     * 网关异常处理
     *
     * @param exchange 当前请求和响应的信息
     * @param ex       异常信息
     * @return 响应式对象
     */
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(ex);
        }

        String message;
        if (ex instanceof NotFoundException) {
            message = "服务未找到";
        } else if (ex instanceof ResponseStatusException) {
            message = ex.getMessage();
        } else {
            message = "内部服务器错误";
        }

        log.error("[网关异常处理] 请求路径:{} 异常信息:{}", exchange.getRequest().getPath(), ex.getMessage());

        return WebFluxUtils.webFluxResponseWriter(response, message);
    }
}
